package org.sp.dao.impl;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.sp.dao.ITestUserDao;
import org.sp.entity.User;
import org.sp.util.HibernateUtil;

import java.io.Serializable;
import java.util.List;

/**
 * @author 76986
 */
public class TestUserDaoImpl implements ITestUserDao {
    private static Session session;

    /**
     * 查询全部用户
     *
     * @return 用户集合
     */
    public TestUserDaoImpl() {
        session = HibernateUtil.getInstance().openSession();
    }

    @Override
    public List<User> queryAllUsers() {
        NativeQuery<User> query = session.createSQLQuery("select * from user");
        query.addEntity(User.class);
        return query.list();
    }

    /**
     * 根据id 删除用户
     *
     * @param id
     * @return true or false
     */
    @Override
    public Boolean deleteUserById(Integer id) {
        String hql = "delete User where id = :ids";
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery(hql);
        query.setParameter("ids", id);
        boolean b = query.executeUpdate() > 0;
        transaction.commit();
        return b;
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @Override
    public Boolean addUser(User user) {
        session.beginTransaction();
        Serializable save = session.save(user);
        session.getTransaction().commit();
        return true;
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @Override
    public Boolean updateUser(User user) {
        String hql = "update User set name=:name,mobile=:mobile,address=:address where id=:id";
        Query<User> query = session.createQuery(hql);
        query.setParameter("name",user.getName());
        query.setParameter("mobile",user.getMobile());
        query.setParameter("address",user.getAddress());
        query.setParameter("id",user.getId());
        Transaction transaction = session.beginTransaction();
        boolean b = query.executeUpdate() > 0;
        transaction.commit();
        return b;
    }

}


